package com.opc.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.opc.Common.Code;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.opc.Common.MessageConstant;
import com.opc.Config.CacheUtil;
import com.opc.Mapper.*;
import com.opc.PojoExt.PositionNameAndTorque;
import com.opc.PojoExt.ScrewTypeAndTorque;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;

import com.opc.Common.Result;
import com.opc.Pojo.*;
import com.opc.PojoExt.CarExt;
import com.opc.PojoExt.CarStatusExt;
import com.opc.Service.*;
import com.opc.properties.IpProperties;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/CarStatus")
public class CarStatusController {

    @Autowired
    private OpcUaService opcUaService;
//    @Autowired
//    private WebSocketServer webSocketServer;
    @Autowired
    private IpProperties ipProperties;
    @Autowired
    private CarStatusMapper carStatusMapper;
    @Autowired
    private CarStatusService carStatusService;
    @Autowired
    private CarMapper carMapper;
    @Autowired
    private ScrewMapper screwMapper;
    @Autowired
    private CarService carService;
    @Autowired
    private ScrewService screwService;
    @Autowired
    private WorkingPositionService workingPositionService;
    @Autowired
    private WeldingGunMapper weldingGunMapper;
    @Autowired
    private ScrewTypeMapper screwTypeMapper;
    @Autowired
    private TorqueStandardsMapper torqueStandardsMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

//    @Value("${screwImageData.path}")
//    private String Screw_image_data;

    //获取所有螺丝类型
    @GetMapping("/getScrewTypeList")
    @CrossOrigin
    public Result getScrewTypeList() {
        LambdaQueryWrapper<screwType> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.select(screwType::getType)
//                .select(screwType::getScrewId)
//                .select(screwType::getWeldingGunId); // 使用 groupBy 确保结果是唯一的

        List<screwType> screwTypeList = screwTypeMapper.selectList(queryWrapper);
//        screwTypeList.forEach(screwType -> {
//            //Screw_image_data+
//            screwType.setImagePath(screwType.getImagePath());
//        });

//        List<String> screwTypeList = screwTypeMapper.selectObjs(queryWrapper).stream()
//                .map(Object::toString) // 转换类型
//                .collect(Collectors.toList());
//        log.info("获取所有螺丝类型"+screwTypeList.stream().distinct());
        if(screwTypeList.isEmpty()){
            return new Result(Code.SELECT_ERR,"没有螺丝类型数据");
        }
        return new Result(Code.SELECT_OK, screwTypeList);
    }

    //获取所有车型
    @GetMapping("/getCarType")
    @CrossOrigin
    public Result getCarType() {
//        LambdaQueryWrapper<Car> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<TorqueStandards> queryWrapper = new LambdaQueryWrapper<>();


//        queryWrapper.orderByDesc(Car::getCreateTime);
//        queryWrapper.groupBy(Car::getCarType);
//        queryWrapper.select(Car::getCarType);
        queryWrapper
                .groupBy(TorqueStandards::getCarType)
                .select(TorqueStandards::getCarType);// 使用 groupBy 确保结果是唯一的
//        List<Car> carTypeList = carMapper.selectList(queryWrapper);
        // 执行查询，获取所有车型
//        List<String> carTypeList = carMapper.selectObjs(queryWrapper).stream()
//                .map(Object::toString) // 转换类型
//                .collect(Collectors.toList());
        List<String> carTypeList = torqueStandardsMapper.selectObjs(queryWrapper).stream()
                .filter(obj -> obj != null && !obj.toString().trim().isEmpty()) // 过滤掉 null 和空格字符串
                .map(Object::toString) // 转换类型
                .collect(Collectors.toList());

        //System.out.println("获取所有车型"+carTypeList);
        if(carTypeList.isEmpty()){
            return new Result(Code.SELECT_ERR,"没有车型数据");
        }
        return new Result(Code.SELECT_OK, carTypeList);
    }

    //获取所有车身号
    @GetMapping("/getCarNum")
    @CrossOrigin
    public Result getCarNum() {
        LambdaQueryWrapper<Car> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Car::getCarId)
                .groupBy(Car::getCarId); // 使用 groupBy 确保结果是唯一的
        // 执行查询，获取所有车身号
//        List<String> carNumList = carMapper.selectObjs(queryWrapper).stream()
//                .map(Object::toString) // 转换类型
//                .collect(Collectors.toList());
        List<String> carNumList = carMapper.selectObjs(queryWrapper).stream()
                .filter(obj -> obj != null && !obj.toString().trim().isEmpty()) // 过滤掉 null 和空格字符串
                .map(Object::toString) // 转换类型
                .collect(Collectors.toList());
//        log.info("获取所有车身号"+carNumList);
        if(carNumList.isEmpty()){
            return new Result(Code.SELECT_ERR,"没有车身号数据");
        }
        return new Result(Code.SELECT_OK, carNumList);
    }

    private static String convertLocalDateTimeToString(Date Time) {
        LocalDateTime localDateTime = Time.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
        String formattedTime = String.format("%04d:%02d:%02d:%02d:%02d",
                localDateTime.getYear(),
                localDateTime.getMonthValue(),
                localDateTime.getDayOfMonth(),
                localDateTime.getHour(),
                localDateTime.getMinute());
//        log.info("formattedTime是"+formattedTime);
        // 使用 replace() 方法替换第一个 ':' 为 '-'
        // 使用正则表达式替换前两个 ':' 为 '-'
        // 拆分字符串
        String[] parts = formattedTime.split(":");
        // 重新组装字符串
        String newFormattedTime = String.join("-", parts[0], parts[1]) + "-" + parts[2] + " " + parts[3] + ":" + parts[4];
//        log.info("timeFormatter是"+newFormattedTime);
        return newFormattedTime;
    }

    //优化后：
    @PostMapping(value = "/getStatisticsData", consumes = MediaType.APPLICATION_JSON_VALUE)
    @CrossOrigin
    @Async//("statisticsThreadPool") // 异步处理，释放Web线程
    public CompletableFuture<Result> getStatisticsData(@RequestBody QueryStatisticsDataCondition condition) {
        log.info("getStatisticsData线程: {}({})", Thread.currentThread().getId(), Thread.currentThread().getName());
        log.info("查询条件: {}", condition);

        return CompletableFuture.supplyAsync(() -> {
            try {
                // 1. 构建分页和查询条件
                Page<Car> carPage = new Page<>(condition.getPage(), condition.getPageSize());
                LambdaQueryWrapper<Car> carQuery = buildCarQueryWrapper(condition);

                // 2. 分页查询车辆（仅查一次，避免重复）
                IPage<Car> pageResult = carService.page(carPage, carQuery);
                if (pageResult.getRecords().isEmpty()) {
                    return new Result(Code.SELECT_ERR, "没有车辆数据");
                }

                // 3. 转换为CarExt并填充螺丝数据（批量处理）
                Page<CarExt> carExtPage = convertToCarExtPage(pageResult);

                return new Result(Code.SELECT_OK, carExtPage);
            } catch (Exception e) {
                log.error("统计数据查询异常", e);
                return new Result(Code.SYSTEM_ERR, "系统异常，请重试");
            }
        });
    }

    // 构建车辆查询条件
    private LambdaQueryWrapper<Car> buildCarQueryWrapper(QueryStatisticsDataCondition condition) {
        LambdaQueryWrapper<Car> query = new LambdaQueryWrapper<>();
        // 车身号查询
        if (StringUtils.hasText(condition.getCarId())) {
            query.like(Car::getCarId, condition.getCarId());
        }
        // 车型查询
        if (StringUtils.hasText(condition.getCarType())) {
            query.eq(Car::getCarType, condition.getCarType());
        }
        // 时间范围查询（优化时区处理）
        List<LocalDateTime> dateRange = condition.getDateRange();
        if (dateRange != null && dateRange.size() == 2) {
            LocalDateTime start = dateRange.get(0).plusHours(8); // 时区调整
            LocalDateTime end = dateRange.get(1).plusHours(8).plusSeconds(1); // 闭区间转开区间
            query.between(Car::getCreateTime, start, end);
        }
        // 排序
        query.orderByDesc(Car::getCreateTime);
        return query;
    }

    // 转换为CarExt分页对象（核心优化：批量查询替代循环查询）
    private Page<CarExt> convertToCarExtPage(IPage<Car> carPage) {
        Page<CarExt> extPage = new Page<>();
        BeanUtils.copyProperties(carPage, extPage, "records");

        // 3.1 提取所有车辆ID，批量查询螺丝（减少SQL次数）
        List<Long> carIds = carPage.getRecords().stream()
                .map(Car::getId)
                .collect(Collectors.toList());
        List<Screw> allScrews = batchGetScrewsByCarIds(carIds); // 批量查螺丝
        Map<Long, List<Screw>> carScrewsMap = groupScrewsByCarId(allScrews); // 按车辆ID分组

        // 3.2 批量查询螺丝类型（避免循环查库）
        Set<Long> screwTypeIds = allScrews.stream()
                .map(Screw::getScrewTypeId)
                .collect(Collectors.toSet());
        Map<Long, screwType> screwTypeMap = batchGetScrewTypes(screwTypeIds); // 批量查螺丝类型

        // 3.3 批量查询车辆状态（避免循环查库）
        Set<Long> screwIds = allScrews.stream()
                .map(Screw::getId)
                .collect(Collectors.toSet());
        Map<Long, CarStatus> screwStatusMap = batchGetCarStatusByScrewIds(screwIds); // 批量查状态

        // 3.4 转换为CarExt列表
        List<CarExt> extList = carPage.getRecords().stream()
                .map(car -> convertToCarExt(car, carScrewsMap, screwTypeMap, screwStatusMap))
                .collect(Collectors.toList());
        extPage.setRecords(extList);

        return extPage;
    }

    // 单辆车转换为CarExt
    private CarExt convertToCarExt(Car car,
                                   Map<Long, List<Screw>> carScrewsMap,
                                   Map<Long, screwType> screwTypeMap,
                                   Map<Long, CarStatus> screwStatusMap) {
        CarExt carExt = new CarExt();
        BeanUtils.copyProperties(car, carExt);
        //.setCarNum
        if(car.getCarId().contains("-")){
            String result = replaceUpToThirdHyphen(car.getCarId(), "***");
            carExt.setCarId(result);
        }
        // 格式化时间
        carExt.setCreateTimeString(convertLocalDateTimeToString(car.getCreateTime()));
        carExt.setUpdateTimeString(convertLocalDateTimeToString(car.getUpdateTime()));

        // 处理当前车的螺丝数据
        List<Screw> screws = carScrewsMap.getOrDefault(car.getId(), Collections.emptyList());
        List<PositionNameAndTorque> positionList = screws.stream()
                .map(screw -> buildPositionData(screw, screwTypeMap, screwStatusMap))
                .collect(Collectors.toList());
        carExt.setPositionNameAndTorqueList(positionList);

        return carExt;
    }

    // 构建单个螺丝的位置和扭矩数据（提取重复逻辑）
    private PositionNameAndTorque buildPositionData(Screw screw,
                                                    Map<Long, screwType> screwTypeMap,
                                                    Map<Long, CarStatus> statusMap) {
        PositionNameAndTorque positionData = new PositionNameAndTorque();
        screwType screwType = screwTypeMap.get(screw.getScrewTypeId());
        CarStatus carStatus = statusMap.get(screw.getId());

        // 设置位置名称（用策略模式替代冗长的if-else）
        positionData.setPositionName(getPositionName(screw.getScrewTypeId()));

        // 构建螺丝扭矩数据
        ScrewTypeAndTorque torqueData = new ScrewTypeAndTorque();
//        torqueData.setCarId(screw.getCarId());
        torqueData.setScrewId(screw.getId());
        torqueData.setScrewTypeId(screw.getScrewTypeId());
        torqueData.setTorque(screw.getTorque());
        torqueData.setCreateTime(convertLocalDateTimeToString(screw.getCreateTime()));
        torqueData.setWorkingPositionId(screw.getWorkingPositionId());

        // 填充螺丝类型信息
        if (screwType != null) {
            torqueData.setGunNum(String.valueOf(screwType.getWeldingGunId()));
            torqueData.setScrewType(String.valueOf(screwType.getType()));
        }

        // 填充状态信息
        if (carStatus != null) {
            torqueData.setAlarmLevel(carStatus.getAlarmLevel().toString());
            torqueData.setAlarmStatus(carStatus.getAlarmStatus().toString());
            torqueData.setNgTorque(carStatus.getTorque());
            torqueData.setCheckStatus(carStatus.getCheckStatus().toString());
            // 处理检查时间
            if (!carStatus.getCreateTime().equals(carStatus.getUpdateTime())) {
                torqueData.setCheckTime(convertLocalDateTimeToString(carStatus.getUpdateTime()));
            }
            if(carStatus.getEmployeeName() != null
            && carStatus.getAlarmLevel().equals(CarStatus.AlarmLevel.danger)){
                // 处理检查人员
                torqueData.setEmployeeName(carStatus.getEmployeeName());
            }
        }

        positionData.setScrewTypeAndTorque(torqueData);
        return positionData;
    }

// ------------------------------
// 以下是批量查询和工具方法（抽取到Service层更佳）
// ------------------------------

    // 批量查询螺丝
    private List<Screw> batchGetScrewsByCarIds(List<Long> carIds) {
        if (carIds.isEmpty()) return Collections.emptyList();
        LambdaQueryWrapper<Screw> query = new LambdaQueryWrapper<>();
        query.in(Screw::getCarId, carIds);
        return screwMapper.selectList(query);
    }

    // 螺丝按车辆ID分组
    private Map<Long, List<Screw>> groupScrewsByCarId(List<Screw> screws) {
        return screws.stream()
                .collect(Collectors.groupingBy(Screw::getCarId));
    }

    // 批量查询螺丝类型
    private Map<Long, screwType> batchGetScrewTypes(Set<Long> typeIds) {
        if (typeIds.isEmpty()) return Collections.emptyMap();
        LambdaQueryWrapper<screwType> query = new LambdaQueryWrapper<>();
        query.in(screwType::getId, typeIds);
        return screwTypeMapper.selectList(query).stream()
                .collect(Collectors.toMap(screwType::getId, Function.identity()));
    }

    // 批量查询车辆状态
    private Map<Long, CarStatus> batchGetCarStatusByScrewIds(Set<Long> screwIds) {
        if (screwIds.isEmpty()) return Collections.emptyMap();
        LambdaQueryWrapper<CarStatus> query = new LambdaQueryWrapper<>();
        query.in(CarStatus::getScrewId, screwIds);
        return carStatusMapper.selectList(query).stream()
                .collect(Collectors.toMap(CarStatus::getScrewId, Function.identity()));
    }

    // 工具方法：根据螺丝类型ID获取位置名称
    private String getPositionName(Long screwTypeId) {
        if (screwTypeId >= 1 && screwTypeId <= 8) return "左上";
        if (screwTypeId >= 9 && screwTypeId <= 16) return "左下";
        if (screwTypeId >= 17 && screwTypeId <= 18) return "右上";
        if (screwTypeId >= 19 && screwTypeId <= 20) return "右下";
        return "未知位置";
    }

    // 时间格式化工具（提取为公共方法）
    private String convertLocalDateTimeToString(LocalDateTime time) {
        return time == null ? null : DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(time);
    }

    //--------------------------------------------
    //优化前：
    /**
     * 获取每辆车的报警统计数据
     * @param
     * @return
     */
//    @Transactional
////    @CrossOrigin(origins ="http://getStatisticsData/{currentPage}/{pageSize}")
//    @PostMapping(value = "/getStatisticsData",
//            consumes = MediaType.APPLICATION_JSON_VALUE) //@RequestBody NodeId[] nodeIds
//    public Result getStatisticsData(@RequestBody QueryStatisticsDataCondition queryStatisticsDataCondition) {
//        log.info("getStatisticsData的线程id:{}", Thread.currentThread().getId()+"名"+Thread.currentThread().getName());
//
//        log.info("进入getStatisticsData"+queryStatisticsDataCondition);
//        Page<Car> iPage=new Page<>(queryStatisticsDataCondition.getPage(),
//                queryStatisticsDataCondition.getPageSize());
//        LambdaQueryWrapper<Car> queryCarWrapper = new LambdaQueryWrapper<>();
//        //不加条件就是查询所有，获取所有车的所有报警统计数据
////        搜索框1根据车身号查询
//        queryCarWrapper.eq(queryStatisticsDataCondition.getCarId()!=null
//                        && !queryStatisticsDataCondition.getCarId().isEmpty(),
//                Car::getCarId,queryStatisticsDataCondition.getCarId());
//        //搜索框2根据车型查询
//        queryCarWrapper.eq(queryStatisticsDataCondition.getCarType()!=null
//                        && !queryStatisticsDataCondition.getCarType().isEmpty(),
//                Car::getCarType,queryStatisticsDataCondition.getCarType());
//
////        搜索框3根据时间范围搜索
//        List<LocalDateTime> dateRange = queryStatisticsDataCondition.getDateRange();
//        if (dateRange != null && dateRange.size() == 2) {
//            log.info("dateRange.get(0)是"+dateRange.get(0).plusDays(1));
//            log.info("dateRange.get(1)是"+dateRange.get(1).plusDays(1));
//
//            LocalDateTime midnightDateTime1 = dateRange.get(0).plusHours(8);
//            LocalDateTime midnightDateTime2 = dateRange.get(1).plusHours(8);
//
//            log.info("midnightDateTime1"+midnightDateTime1);
//            log.info("midnightDateTime2"+midnightDateTime2);
//
//            queryCarWrapper.between(Car::getCreateTime, midnightDateTime1, midnightDateTime2);
//        }
//
//        queryCarWrapper.orderByDesc(Car::getCreateTime);
//        List<Car> cars = carMapper.selectList(queryCarWrapper);
//        if(cars.isEmpty()){
//            return new Result(Code.SELECT_ERR,"没有车辆数据");
//        }
////        log.info("cars:"+cars);
//
//        Page<CarExt> iPageExt=new Page<>();
//        IPage<Car> pageResult = carService.page(iPage,queryCarWrapper);
//        BeanUtils.copyProperties(iPage,iPageExt,"records");
//        //从iPage一个一个拷贝属性到iPageExt上(除了records)
//        List<Car> records = iPage.getRecords();
//        List<CarExt> list = records.stream().map((item) -> {
//            CarExt carExt = new CarExt();
//
//            String newFormattedCreateTime = convertLocalDateTimeToString(item.getCreateTime());
//            String newFormattedUpdateTime = convertLocalDateTimeToString(item.getUpdateTime());
//
//            BeanUtils.copyProperties(item,carExt);
//            carExt.setCreateTimeString(newFormattedCreateTime);
//            carExt.setUpdateTimeString(newFormattedUpdateTime);
//            LambdaQueryWrapper<Screw> queryWrapper = new LambdaQueryWrapper<>();
//            //先拿到这辆车的所有螺丝
//            queryWrapper.eq(Screw::getCarId, item.getId());
//            List<Screw> screws = screwMapper.selectList(queryWrapper);
////            log.info("screws:"+screws);
//            List<PositionNameAndTorque> positionNameAndTorqueList = new ArrayList<>();
//            //分类(每辆车有4个PositionName，所以要放近car的循环里)
//            for (Screw screw : screws) {
//                ScrewTypeAndTorque screwTypeAndTorque = new ScrewTypeAndTorque();
////                List<ScrewTypeAndTorque> screwTypeAndTorqueList = new ArrayList<>();
//                PositionNameAndTorque positionNameAndTorque = new PositionNameAndTorque();
//                Long screwTypeId = screw.getScrewTypeId();
//                LambdaQueryWrapper<screwType> queryWrapper1 = new LambdaQueryWrapper<>();
//                queryWrapper1.eq(screwType::getId,screwTypeId);
//                screwType screwType = screwTypeMapper.selectOne(queryWrapper1);
//                log.info("screwType.getImagePath()"+screwType.getImagePath());
//                if(screwTypeId >= 1 && screwTypeId <= 8){
//                    positionNameAndTorque.setPositionName("左上");
//                    screwTypeAndTorque.setScrewTypeId(screwTypeId);
////                    screwTypeAndTorque.setImagePath(Screw_image_data+screwType.getImagePath());
//                    screwTypeAndTorque.setScrewId(screw.getId());
//                    screwTypeAndTorque.setGunNum(String.valueOf(screwType.getWeldingGunId()));
//                    LambdaQueryWrapper<CarStatus> carStatusQueryWrapper = new LambdaQueryWrapper<>();
//                    carStatusQueryWrapper.eq(CarStatus::getScrewId,screw.getId());
//                    CarStatus carStatus = carStatusMapper.selectOne(carStatusQueryWrapper);
////                     && carStatus.getAlarmLevel().equals(CarStatus.AlarmLevel.danger)
//                    if(carStatus != null){
//                        screwTypeAndTorque.setAlarmLevel(carStatus.getAlarmLevel().toString());
//                        screwTypeAndTorque.setAlarmStatus(carStatus.getAlarmStatus().toString());
//                        screwTypeAndTorque.setNgTorque(carStatus.getTorque());
//                    }
//                    screwTypeAndTorque.setCreateTime(convertLocalDateTimeToString(screw.getCreateTime()));
//                    if(carStatus != null){
//                        if(carStatus.getCreateTime() != carStatus.getUpdateTime()){
//                            screwTypeAndTorque.setCheckTime(convertLocalDateTimeToString(carStatus.getUpdateTime()));
//                        }
//                        screwTypeAndTorque.setCheckStatus(carStatus.getCheckStatus().toString());
//                    }
//                    screwTypeAndTorque.setWorkingPositionId(screw.getWorkingPositionId());
//                    screwTypeAndTorque.setScrewType(String.valueOf(screwType.getType()));
//                    screwTypeAndTorque.setTorque(screw.getTorque());
////                    screwTypeAndTorqueList.add(screwTypeAndTorque);
//                    positionNameAndTorque.setScrewTypeAndTorque(screwTypeAndTorque);
//                }
//
//                if(screwTypeId >= 9 && screwTypeId <= 16){
////                    ScrewTypeAndTorque screwTypeAndTorque = new ScrewTypeAndTorque();
//                    positionNameAndTorque.setPositionName("左下");
//                    screwTypeAndTorque.setScrewTypeId(screwTypeId);
////                    screwTypeAndTorque.setImagePath(Screw_image_data+screwType.getImagePath());
//                    screwTypeAndTorque.setScrewId(screw.getId());
//                    screwTypeAndTorque.setGunNum(String.valueOf(screwType.getWeldingGunId()));
//                    LambdaQueryWrapper<CarStatus> carStatusQueryWrapper = new LambdaQueryWrapper<>();
//                    carStatusQueryWrapper.eq(CarStatus::getScrewId,screw.getId());
//                    CarStatus carStatus = carStatusMapper.selectOne(carStatusQueryWrapper);
////                     && carStatus.getAlarmLevel().equals(CarStatus.AlarmLevel.danger)
//                    if(carStatus != null){
//                        screwTypeAndTorque.setAlarmLevel(carStatus.getAlarmLevel().toString());
//                        screwTypeAndTorque.setAlarmStatus(carStatus.getAlarmStatus().toString());
//                        screwTypeAndTorque.setNgTorque(carStatus.getTorque());
//                    }
//                    screwTypeAndTorque.setCreateTime(convertLocalDateTimeToString(screw.getCreateTime()));
//                    if(carStatus != null){
//                        if(carStatus.getCreateTime() != carStatus.getUpdateTime()){
//                            screwTypeAndTorque.setCheckTime(convertLocalDateTimeToString(carStatus.getUpdateTime()));
//                        }
//                        screwTypeAndTorque.setCheckStatus(carStatus.getCheckStatus().toString());
//                    }
//                    screwTypeAndTorque.setWorkingPositionId(screw.getWorkingPositionId());
//                    screwTypeAndTorque.setScrewType(String.valueOf(screwType.getType()));
//                    screwTypeAndTorque.setTorque(screw.getTorque());
////                    screwTypeAndTorqueList.add(screwTypeAndTorque);
//                    positionNameAndTorque.setScrewTypeAndTorque(screwTypeAndTorque);
//                }
//                if(screwTypeId >= 17 && screwTypeId <= 18){
////                    ScrewTypeAndTorque screwTypeAndTorque = new ScrewTypeAndTorque();
//                    positionNameAndTorque.setPositionName("右上");
//                    screwTypeAndTorque.setScrewTypeId(screwTypeId);
////                    screwTypeAndTorque.setImagePath(Screw_image_data+screwType.getImagePath());
//                    screwTypeAndTorque.setScrewId(screw.getId());
//                    screwTypeAndTorque.setGunNum(String.valueOf(screwType.getWeldingGunId()));
//                    LambdaQueryWrapper<CarStatus> carStatusQueryWrapper = new LambdaQueryWrapper<>();
//                    carStatusQueryWrapper.eq(CarStatus::getScrewId,screw.getId());
//                    CarStatus carStatus = carStatusMapper.selectOne(carStatusQueryWrapper);
////                     && carStatus.getAlarmLevel().equals(CarStatus.AlarmLevel.danger)
//                    if(carStatus != null){
//                        screwTypeAndTorque.setAlarmLevel(carStatus.getAlarmLevel().toString());
//                        screwTypeAndTorque.setAlarmStatus(carStatus.getAlarmStatus().toString());
//                        screwTypeAndTorque.setNgTorque(carStatus.getTorque());
//                    }
//                    screwTypeAndTorque.setCreateTime(convertLocalDateTimeToString(screw.getCreateTime()));
//                    if(carStatus != null){
//                        if(carStatus.getCreateTime() != carStatus.getUpdateTime()){
//                            screwTypeAndTorque.setCheckTime(convertLocalDateTimeToString(carStatus.getUpdateTime()));
//                        }
//                        screwTypeAndTorque.setCheckStatus(carStatus.getCheckStatus().toString());
//                    }
//                    screwTypeAndTorque.setWorkingPositionId(screw.getWorkingPositionId());
//                    screwTypeAndTorque.setScrewType(String.valueOf(screwType.getType()));
//                    screwTypeAndTorque.setTorque(screw.getTorque());
////                    screwTypeAndTorqueList.add(screwTypeAndTorque);
//                    positionNameAndTorque.setScrewTypeAndTorque(screwTypeAndTorque);
//                }
//                if(screwTypeId >= 19 && screwTypeId <= 20){
////                    ScrewTypeAndTorque screwTypeAndTorque = new ScrewTypeAndTorque();
//                    positionNameAndTorque.setPositionName("右下");
//                    screwTypeAndTorque.setScrewTypeId(screwTypeId);
////                    screwTypeAndTorque.setImagePath(Screw_image_data+screwType.getImagePath());
//                    screwTypeAndTorque.setScrewId(screw.getId());
//                    screwTypeAndTorque.setGunNum(String.valueOf(screwType.getWeldingGunId()));
//                    LambdaQueryWrapper<CarStatus> carStatusQueryWrapper = new LambdaQueryWrapper<>();
//                    carStatusQueryWrapper.eq(CarStatus::getScrewId,screw.getId());
//                    CarStatus carStatus = carStatusMapper.selectOne(carStatusQueryWrapper);
////                     && carStatus.getAlarmLevel().equals(CarStatus.AlarmLevel.danger)
//                    if(carStatus != null){
//                        screwTypeAndTorque.setAlarmLevel(carStatus.getAlarmLevel().toString());
//                        screwTypeAndTorque.setAlarmStatus(carStatus.getAlarmStatus().toString());
//                        screwTypeAndTorque.setNgTorque(carStatus.getTorque());
//                    }
//                    screwTypeAndTorque.setCreateTime(convertLocalDateTimeToString(screw.getCreateTime()));
//                    if(carStatus != null){
//                        if(carStatus.getCreateTime() != carStatus.getUpdateTime()){
//                            screwTypeAndTorque.setCheckTime(convertLocalDateTimeToString(carStatus.getUpdateTime()));
//                        }
//                        screwTypeAndTorque.setCheckStatus(carStatus.getCheckStatus().toString());
//                    }
//                    screwTypeAndTorque.setWorkingPositionId(screw.getWorkingPositionId());
//                    screwTypeAndTorque.setScrewType(String.valueOf(screwType.getType()));
//                    screwTypeAndTorque.setTorque(screw.getTorque());
////                    screwTypeAndTorqueList.add(screwTypeAndTorque);
//                    positionNameAndTorque.setScrewTypeAndTorque(screwTypeAndTorque);
//                }
//                positionNameAndTorqueList.add(positionNameAndTorque);
//            }
//
//            carExt.setPositionNameAndTorqueList(positionNameAndTorqueList);
//            return carExt;
//        }).collect(Collectors.toList());
//        iPageExt.setRecords(list);
////        log.info("pageResult.getTotal()是:"+pageResult.getTotal());
////        iPageExt.setTotal(pageResult.getTotal()); // 设置总记录数，添加MybatisPlusConfig就能解决
////        return new Result(Code.SELECT_ERR,"没有数据");
//        return new Result(Code.SELECT_OK,iPageExt);
//    }

//    @PostMapping(value = "/getStatisticsData/{currentPage}/{pageSize}",
//            consumes = MediaType.APPLICATION_JSON_VALUE) //@RequestBody NodeId[] nodeIds
//    public Result getStatisticsData(@PathVariable int currentPage,
//                                    @PathVariable int pageSize) {
////                                    @RequestBody QueryStatisticsDataCondition queryStatisticsDataCondition) {
////        +queryStatisticsDataCondition
//        log.info("进入getStatisticsData");
//        Page<Car> iPage=new Page<>(currentPage,pageSize);
//        LambdaQueryWrapper<Car> queryCarWrapper = new LambdaQueryWrapper<>();
//        //不加条件就是查询所有，获取所有车的所有报警统计数据
//        //搜索框1根据车身号查询
////        queryCarWrapper.like(queryStatisticsDataCondition.getCarId()!=null
////                        && !queryStatisticsDataCondition.getCarId().isEmpty(),
////                Car::getCarId,queryStatisticsDataCondition.getCarId());
////        //搜索框2根据车型查询
////        queryCarWrapper.eq(queryStatisticsDataCondition.getCarType()!=null
////                        && !queryStatisticsDataCondition.getCarType().isEmpty(),
////                Car::getCarType,queryStatisticsDataCondition.getCarType());
//        //搜索框3根据时间范围搜索
////        List<LocalDateTime> dateRange = queryStatisticsDataCondition.getDateRange();
////        if (dateRange != null && dateRange.size() == 2) {
//////            LocalDate startDate = LocalDate.from(dateRange.get(0).plusDays(1).toLocalDate().atStartOfDay()); // 由于时区的影响，需要加一天
//////            LocalDate endDate = LocalDate.from(dateRange.get(1).plusDays(1).toLocalDate().atStartOfDay());
////            // 获取开始和结束的日期和时间
////            LocalDateTime startDate = dateRange.get(0); // 获取开始时间，假设这是一个 LocalDateTime
////            log.info("startDate是"+startDate);
////            LocalDateTime endDate = dateRange.get(1);   // 获取结束时间，假设这是一个 LocalDateTime
////            log.info("endDate是"+endDate);
////
//////            LocalDateTime startDate = LocalDateTime.of(year, month, day, hour, minute, second); // 开始时间
//////            LocalDateTime endDate = LocalDateTime.of(year, month, day, hour, minute, second);   // 结束时间
////
////            queryCarWrapper.between(Car::getCreateTime, startDate, endDate);
////        }
////        if (dateRange != null && dateRange.size() == 2) {
////            // 获取开始和结束时间并转换为 LocalDateTime，注意不需要加一天
////            LocalDateTime startDate = dateRange.get(0).toLocalDate().atStartOfDay(); // 开始时间
////            LocalDateTime endDate = dateRange.get(1).toLocalDate().atTime(23, 59, 59); // 结束时间到当日23:59:59
////
////            // 添加查询条件
////            queryCarWrapper.between(Car::getCreateTime, startDate, endDate);
////        }
//
//        //根据工位查询报警
////        queryCarWrapper.eq(queryStatisticsDataCondition.getWorkingPositionId()!=null
////                        && !queryStatisticsDataCondition.getWorkingPositionId().isEmpty(),
////                Car::getWorkingPositionId,queryStatisticsDataCondition.getWorkingPositionId());
//
//        queryCarWrapper.orderByAsc(Car::getCreateTime);
//        List<Car> cars = carMapper.selectList(queryCarWrapper);
//        if(cars.isEmpty()){
//            return new Result(Code.SELECT_ERR,"没有车辆数据");
//        }
//        log.info("cars:"+cars);
//
//        Page<CarExt> iPageExt=new Page<>();
//        carService.page(iPage,queryCarWrapper);
//        BeanUtils.copyProperties(iPage,iPageExt,"records");
//        //从iPage一个一个拷贝属性到iPageExt上(除了records)
//        List<Car> records = iPage.getRecords();
//        List<PositionNameAndTorque> positionNameAndTorqueList = new ArrayList<>();
//        List<CarExt> list = records.stream().map((item) -> {
//            CarExt carExt = new CarExt();
//            BeanUtils.copyProperties(item,carExt);
//
////            WorkingPosition workingPosition = workingPositionService.getById(item.getWorkingPositionId());
////            if(workingPosition != null){
////                carExt.setWorkingPositionName(workingPosition.getWeldingGunName());
////            }
//
//            LambdaQueryWrapper<Screw> queryWrapper = new LambdaQueryWrapper<>();
//            //先拿到这辆车的所有螺丝
//            queryWrapper.eq(Screw::getCarId, item.getId());
//            List<Screw> screws = screwMapper.selectList(queryWrapper);
//            log.info("screws:"+screws);
//            //分类(每辆车有4个PositionName，所以要放近car的循环里)
//            PositionNameAndTorque positionNameAndTorque = new PositionNameAndTorque();
//
//            List<ScrewTypeAndTorque> screwTypeAndTorqueList = new ArrayList<>();
//            if(!screws.isEmpty()){
//
//                for(Screw screw : screws){
//                    if (screw.getWorkingPositionId().equals(MessageConstant.workingPosition1)) {
//                        LambdaQueryWrapper<screwType> screwTypeQueryWrapper = new LambdaQueryWrapper<>();
//                        screwTypeQueryWrapper.eq(screwType::getId, screw.getScrewTypeId());
//                        screwType screwType = screwTypeMapper.selectOne(screwTypeQueryWrapper);
//                        if(screwType.getWeldingGunId().toString().equals(MessageConstant.gun1Num)){
//                            positionNameAndTorque.setPositionName("左上");
//                            LambdaQueryWrapper<Screw> queryScrewWrapper = new LambdaQueryWrapper<>();
//                            //工位一
//                            queryScrewWrapper.eq(Screw::getWorkingPositionId, MessageConstant.workingPosition1);
//                            //上半部分
//                            queryScrewWrapper.between(Screw::getScrewTypeId, 1, 8);
////                           queryScrewWrapper.eq(Screw::getWeldingGunId, MessageConstant.gun1Num);
//                            //所有的螺丝
//                            List<Screw> screws1 = screwMapper.selectList(queryScrewWrapper);
//                            ScrewTypeAndTorque screwTypeAndTorque = new ScrewTypeAndTorque();
//                            for (Screw screw1 : screws1) {
//                                screwTypeAndTorque.setScrewTypeId(String.valueOf(screw1.getScrewTypeId()));
//                                screwTypeAndTorque.setTorque(screw1.getTorque());
//                            }
//                            screwTypeAndTorqueList.add(screwTypeAndTorque);
////                           positionNameAndTorque.setScrewTypeAndTorqueList(screwTypeAndTorqueList);
//                        }else if (screwType.getWeldingGunId().toString().equals(MessageConstant.gun2Num)) {
//                            positionNameAndTorque.setPositionName("左下");
//                            List<ScrewTypeAndTorque> screwNumAndTorqueList = new ArrayList<>();
//
//                            LambdaQueryWrapper<Screw> queryScrewWrapper = new LambdaQueryWrapper<>();
//                            //工位一
//                            queryScrewWrapper.eq(Screw::getWorkingPositionId, MessageConstant.workingPosition1);
//                            //下半部分
//                            queryScrewWrapper.between(Screw::getScrewTypeId, 9, 16);
////                           queryScrewWrapper.eq(Screw::getWeldingGunId, MessageConstant.gun2Num);
//                            //所有的螺丝
//                            List<Screw> screws2 = screwMapper.selectList(queryScrewWrapper);
//                            ScrewTypeAndTorque screwNumAndTorque = new ScrewTypeAndTorque();
//                            for (Screw screw2 : screws2) {
//                                screwNumAndTorque.setScrewTypeId(String.valueOf(screw2.getScrewTypeId()));
//                                screwNumAndTorque.setTorque(screw2.getTorque());
//                            }
//                            screwNumAndTorqueList.add(screwNumAndTorque);
////                           positionNameAndTorque.setScrewTypeAndTorqueList(screwNumAndTorqueList);
//                        }
//                    } else if(screw.getWorkingPositionId().equals(MessageConstant.workingPosition2)){
//                        LambdaQueryWrapper<screwType> screwTypeQueryWrapper = new LambdaQueryWrapper<>();
//                        screwTypeQueryWrapper.eq(screwType::getId, screw.getScrewTypeId());
//                        screwType screwType = screwTypeMapper.selectOne(screwTypeQueryWrapper);
//                        if (screwType.getWeldingGunId().toString().equals(MessageConstant.gun3Num)) {
//                            positionNameAndTorque.setPositionName("右上");
//                            List<ScrewTypeAndTorque> screwNumAndTorqueList = new ArrayList<>();
//
//                            LambdaQueryWrapper<Screw> queryScrewWrapper = new LambdaQueryWrapper<>();
//                            //工位二
//                            queryScrewWrapper.eq(Screw::getWorkingPositionId, MessageConstant.workingPosition2);
//                            //上半部分
//                            queryScrewWrapper.between(Screw::getScrewTypeId, 17, 18);
////                            queryScrewWrapper.eq(Screw::getWeldingGunId, MessageConstant.gun3Num);
//                            //所有的螺丝
//                            List<Screw> screws3 = screwMapper.selectList(queryScrewWrapper);
//                            for (Screw screw3 : screws3) {
//                                ScrewTypeAndTorque screwNumAndTorque = new ScrewTypeAndTorque();
//                                screwNumAndTorque.setScrewTypeId(String.valueOf(screw3.getScrewTypeId()));
//                                screwNumAndTorque.setTorque(screw3.getTorque());
//                                screwNumAndTorqueList.add(screwNumAndTorque);
//                            }
////                            positionNameAndTorque.setScrewTypeAndTorqueList(screwNumAndTorqueList);
//                        }else if (screwType.getWeldingGunId().toString().equals(MessageConstant.gun4Num)) {
//                            positionNameAndTorque.setPositionName("右下");
//                            List<ScrewTypeAndTorque> screwNumAndTorqueList = new ArrayList<>();
//
//                            LambdaQueryWrapper<Screw> queryScrewWrapper = new LambdaQueryWrapper<>();
//                            //工位二
//                            queryScrewWrapper.eq(Screw::getWorkingPositionId, MessageConstant.workingPosition2);
//                            //下半部分
//                            queryScrewWrapper.between(Screw::getScrewTypeId, 19, 20);
////                           queryScrewWrapper.eq(Screw::getWeldingGunId, MessageConstant.gun4Num);
//                            //所有的螺丝
//                            List<Screw> screws4 = screwMapper.selectList(queryScrewWrapper);
//                            for (Screw screw4 : screws4) {
//                                ScrewTypeAndTorque screwNumAndTorque = new ScrewTypeAndTorque();
//                                screwNumAndTorque.setScrewTypeId(String.valueOf(screw4.getScrewTypeId()));
//                                screwNumAndTorque.setTorque(screw4.getTorque());
//                                screwNumAndTorqueList.add(screwNumAndTorque);
//                            }
////                           positionNameAndTorque.setScrewTypeAndTorqueList(screwNumAndTorqueList);
//                        }
//                    }
//                    positionNameAndTorque.setScrewTypeAndTorqueList(screwTypeAndTorqueList);
//                }//for 循环结束
//
//            }
//            positionNameAndTorqueList.add(positionNameAndTorque);
//
//            carExt.setPositionNameAndTorqueList(positionNameAndTorqueList);
//
////            //1.根据carId查询数据库，获取今天，昨天，近七天的CarStatus的数据
////            LambdaQueryWrapper<CarStatus> queryCarStatusWrapper = new LambdaQueryWrapper<>();
////            queryCarStatusWrapper.eq(CarStatus::getCarId, item.getId());
////
////            // 获取当前日期
////            LocalDate today = LocalDate.now();
////            LocalDate yesterday = today.minusDays(1);
////            LocalDate sevenDaysAgo = today.minusDays(7);
////
//////            Map<String, List<CarStatus>> map = new HashMap<>();
////
////            // 查询今天的数据
////            queryCarStatusWrapper.ge(CarStatus::getCreateTime, today.atStartOfDay())
////                .lt(CarStatus::getCreateTime, today.plusDays(1).atStartOfDay());
////            List<CarStatus> todayData = carStatusMapper.selectList(queryCarStatusWrapper);
////            queryCarStatusWrapper.clear(); // 清空条件
//////            map.put("today", todayData);
////            carExt.setTodayAlarmCount((long) todayData.size());
////
////            // 查询昨天的数据
////            queryCarStatusWrapper.ge(CarStatus::getCreateTime, yesterday.atStartOfDay())
////                    .lt(CarStatus::getCreateTime, today.atStartOfDay());
////            List<CarStatus> yesterdayData = carStatusMapper.selectList(queryCarStatusWrapper);
////            queryCarStatusWrapper.clear(); // 清空条件
//////            map.put("yesterday", yesterdayData);
////            carExt.setYesterdayAlarmCount((long) yesterdayData.size());
////
////            // 查询近七天的数据
////            queryCarStatusWrapper.ge(CarStatus::getCreateTime, sevenDaysAgo.atStartOfDay())
////                    .lt(CarStatus::getCreateTime, today.plusDays(1).atStartOfDay());
////            List<CarStatus> lastSevenDaysData = carStatusMapper.selectList(queryCarStatusWrapper);
//////            map.put("lastSevenDays", lastSevenDaysData);
////            carExt.setLastSevenDaysAlarmCount((long) lastSevenDaysData.size());
//
//            return carExt;
//        }).collect(Collectors.toList());
//        iPageExt.setRecords(list);
//        return new Result(Code.SELECT_OK,iPageExt);
//    }

//    @PostMapping("/getCarstatusDetailData")
//    public Result getDetailData(@PathVariable int currentPage,
//                                @PathVariable int pageSize,
//                                @PathVariable Long carId){
//        Page<CarStatus> iPage=new Page<>(currentPage,pageSize);
//        //时间、报警内容、是否已查看
//        LambdaQueryWrapper<CarStatus> queryCarStatusWrapper = new LambdaQueryWrapper<>();
//        queryCarStatusWrapper.eq(CarStatus::getCarId,carId);
//        queryCarStatusWrapper.orderByDesc(CarStatus::getCreateTime);
//        List<CarStatus> carStatuses = carStatusMapper.selectList(queryCarStatusWrapper);
//        if(carStatuses.isEmpty()){
//            return new Result(Code.SELECT_ERR,"该车没有报警数据");
//        }
//        Page<CarStatusExt> iPageExt=new Page<>();
//        carStatusService.page(iPage,queryCarStatusWrapper);
//        BeanUtils.copyProperties(iPage,iPageExt,"records");
//        List<CarStatus> records = iPage.getRecords();
//        List<CarStatusExt> list = records.stream().map((item) -> {
//            CarStatusExt carStatusExt = new CarStatusExt();
//            BeanUtils.copyProperties(item,carStatusExt);
//            Car car = carService.getById(item.getCarId());
//            if(car != null){
//                carStatusExt.setCarNum(car.getCarId());
//            }
//            Screw screw = screwService.getById(item.getScrewId());
//            if(screw != null){
//                carStatusExt.setScrewNum(screw.getScrewId());
//            }
//            return carStatusExt;
//        }).collect(Collectors.toList());
//        iPageExt.setRecords(list);
//        return new Result(Code.SELECT_OK,iPageExt);
//    }

    // 单页最大加载的数字
//    private final static short MAX_PAGE_SIZE = 50;


    /**
     * 上拉，加载更多
     * @return
     */
    @PostMapping("/loadmore")//前端设置page计数器，并把计数器数据缓存起来？？？
    @Transactional//, @RequestParam int page
    @CrossOrigin
    public Result loadMore(@RequestBody QueryAlarmDataCondition queryAlarmDataCondition) {
        log.info("loadMore的线程id:{}", Thread.currentThread().getId()+"名"+Thread.currentThread().getName());
        //System.out.println("queryAlarmDataCondition是"+queryAlarmDataCondition);

        int pageSize;
        if(queryAlarmDataCondition.getPageSize() == 0){
            pageSize = 20; // 不传就是每次加载10条数据
        }else {
            pageSize = queryAlarmDataCondition.getPageSize();
        }

        int page;
        if(queryAlarmDataCondition.getPage() == 0) {
            page = 1; // 不传就是每次加载第一页
        }else {
            page = queryAlarmDataCondition.getPage();
        }

//        Page<CarStatus> iPage=new Page<>(queryAlarmDataCondition.getPage(),
//                queryAlarmDataCondition.getPageSize());

        int currentOffset = (page - 1) * pageSize; // 计算当前偏移量
        LambdaQueryWrapper<CarStatus> queryWrapper = new LambdaQueryWrapper<>();

//        // 只查询比上次加载的时间更大的记录
//        queryWrapper.gt(queryAlarmDataCondition.getLastLoadedTime()!=null
//                        && !queryAlarmDataCondition.getLastLoadedTime().isEmpty(),
//                CarStatus::getCreateTime, queryAlarmDataCondition.getLastLoadedTime());

        //搜索框0根据车身号模糊搜索
//        queryWrapper.like(queryAlarmDataCondition.getCarId()!=null
//                        && !queryAlarmDataCondition.getCarId().isEmpty(),
//                CarStatus::getCarId, queryAlarmDataCondition.getCarId());
        //搜索框1哪个工位的警报
        queryWrapper.eq(queryAlarmDataCondition.getWorkingPositionId()!=null
                && !queryAlarmDataCondition.getWorkingPositionId().isEmpty(),
        CarStatus::getWorkingPositionId,queryAlarmDataCondition.getWorkingPositionId());

        //搜索下拉框2螺丝编号 1-20
        if (queryAlarmDataCondition.getScrewTypeId() != null
                && !queryAlarmDataCondition.getScrewTypeId().isEmpty()) {
            queryWrapper.eq(CarStatus::getScrewTypeId, queryAlarmDataCondition.getScrewTypeId());
        }

//        //搜索框3处理情况
//        if (queryAlarmDataCondition.getCheckStatus() != null
//                && !queryAlarmDataCondition.getCheckStatus().isEmpty()) {
//
//            // 2. 新增逻辑：当状态为「待处理」时，关联Car表过滤screwIsNull为null的记录
//            if (queryAlarmDataCondition.getCheckStatus().equals(CarStatus.CheckStatus.waitForCheck.toString())) {
//                // 第一步：查询当天所有 screwIsNull = null 的汽车 ID 列表
//                LambdaQueryWrapper<Car> carQueryWrapper = new LambdaQueryWrapper<>();
//                carQueryWrapper.isNull(Car::getScrewIsNull);
//                carQueryWrapper.eq(Car::getCreateTime, LocalDateTime.now());
//                List<Long> validCarIds = carMapper.selectObjs(carQueryWrapper) // 查 Car.id 列表
//                        .stream()
//                        .map(obj -> (Long) obj) // 转换为 Long 类型（根据你 Car.id 的类型调整）
//                        .toList(); // JDK8+ 用 Collectors.toList()
//
//                // 第二步：CarStatus 的 carId 必须在 validCarIds 中（无符合条件的 Car 则返回空）
//                if (!validCarIds.isEmpty()) {
//                    queryWrapper.in(CarStatus::getCarId, validCarIds)
//                            .or().eq(CarStatus::getCheckStatus, queryAlarmDataCondition.getCheckStatus());
//                }
////                else {
////                    // 无符合条件的 Car，直接添加一个永假条件，避免查询到数据
////                    queryWrapper.eq(CarStatus::getId, -1);
////                }
//            }else{
//                queryWrapper.eq(CarStatus::getCheckStatus, queryAlarmDataCondition.getCheckStatus());
//            }
//        }

        // 搜索框3处理情况
        if (queryAlarmDataCondition.getCheckStatus() != null
                && !queryAlarmDataCondition.getCheckStatus().isEmpty()) {
            String checkStatus = queryAlarmDataCondition.getCheckStatus();
            // 待处理状态（用常量字符串避免重复，且equals顺序反过来防空指针）
            String WAIT_FOR_CHECK = CarStatus.CheckStatus.waitForCheck.toString();

            if (WAIT_FOR_CHECK.equals(checkStatus)) {
                // 第一步：查询「当天创建 + screwIsNull = null」的汽车 ID 列表（修正时间查询逻辑）
                LambdaQueryWrapper<Car> carQueryWrapper = new LambdaQueryWrapper<>();
//                carQueryWrapper.isNull(Car::getScrewIsNull);
                carQueryWrapper.eq(Car::getScrewIsNull, "Null");

                // 修正：只查询当天创建的Car（00:00:00 到 23:59:59.999）
                LocalDateTime todayStart = LocalDateTime.now().with(LocalTime.MIN); // 当天0点
                LocalDateTime todayEnd = LocalDateTime.now().with(LocalTime.MAX); // 当天23:59:59.999
                carQueryWrapper.between(Car::getCreateTime, todayStart, todayEnd);

                // 查Car.id列表（兼容JDK8，用Collectors.toList()）
                List<Long> validCarIds = carMapper.selectObjs(carQueryWrapper)
                        .stream()
                        .map(obj -> (Long) obj) // 按Car.id实际类型调整（如String则转String）
                        .collect(Collectors.toList());

                // 第二步：用or(w -> ...)包裹条件，确保优先级正确（核心修正）
                queryWrapper.or(w -> {
                    // 条件1：关联的Car在validCarIds中
                    if (!validCarIds.isEmpty()) {
                        w.in(CarStatus::getCarId, validCarIds);
                    }
                    // 条件2：CheckStatus = 待处理（无论validCarIds是否为空，都保留该条件）
                    if (validCarIds.isEmpty()) {
                        w.eq(CarStatus::getCheckStatus, checkStatus);
                    } else {
                        w.or().eq(CarStatus::getCheckStatus, checkStatus);
                    }
                });
            } else {
                // 非待处理状态：保留原有逻辑
                queryWrapper.eq(CarStatus::getCheckStatus, checkStatus);
            }
        }

        // 时间范围搜索
        List<LocalDateTime> dateRange = queryAlarmDataCondition.getDateRange();
        if (dateRange != null && dateRange.size() == 2) {
//            log.info("dateRange.get(0)是"+dateRange.get(0).plusDays(1));
//            log.info("dateRange.get(1)是"+dateRange.get(1).plusDays(1));

            LocalDateTime midnightDateTime1 = dateRange.get(0).plusHours(8);
            LocalDateTime midnightDateTime2 = dateRange.get(1).plusHours(8);

//            LocalDateTime midnightDateTime1 = dateRange.get(0).plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
//            LocalDateTime midnightDateTime2 = dateRange.get(1).plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);

//            log.info("midnightDateTime1"+midnightDateTime1);
//            log.info("midnightDateTime2"+midnightDateTime2);

            queryWrapper.between(CarStatus::getCreateTime, midnightDateTime1, midnightDateTime2);
        }
//.eq(CarStatus::getCarId, queryAlarmDataCondition.getCarId())
        queryWrapper.orderByDesc(CarStatus::getCreateTime)
                .last("LIMIT " + currentOffset + "," + pageSize); // 设置偏移量和限制条数


        List<CarStatus> carStatuses = carStatusMapper.selectList(queryWrapper);
//        Page<CarStatus> iPageExt=new Page<>();
//        carStatusService.page(iPage,queryWrapper);


        List<CarStatusExt> carStatusExts = new ArrayList<>();

        for (CarStatus carStatus : carStatuses) {
            CarStatusExt carStatusExt = new CarStatusExt();
            BeanUtils.copyProperties(carStatus, carStatusExt);

            Car car = carService.getById(carStatus.getCarId());
            if (car != null) {
                if(car.getCarId().contains("-")){
                    String result = replaceUpToThirdHyphen(car.getCarId(), "***");
                    carStatusExt.setCarNum(result);
                }else {
                    carStatusExt.setCarNum(car.getCarId());
                }
                carStatusExt.setCarType(car.getCarType());
                carStatusExt.setRepeatNum(car.getRepeatNum());
                //该车螺丝是否有缺失
                if(car.getScrewIsNull()!=null){
                    carStatusExt.setScrewIsNull(car.getScrewIsNull());
                }
            }


            //1.以螺丝为标准
//            Screw screw = screwService.getById(carStatus.getScrewId());
//            if (screw != null) {
//                screwType screwType = screwTypeMapper.selectById(screw.getScrewTypeId());
//                if(screwType!=null) {
//                    carStatusExt.setScrewType(screwType);
//                }
//            }
            //2.以告警为标准
            screwType screwType = screwTypeMapper.selectById(carStatus.getScrewTypeId());
            if(screwType!=null) {
                carStatusExt.setScrewType(screwType);
            }

            carStatusExts.add(carStatusExt);
        }

        if (carStatuses.isEmpty()) {
            return new Result(Code.SELECT_OK, Collections.emptyList());
        }

        return new Result(Code.SELECT_OK, carStatusExts);
    }

    /**
     * 将字符串中第三个"-"及其前面的所有内容替换为指定字符串
     * @param input 输入字符串
     * @param replacement 替换字符串
     * @return 处理后的字符串
     */
    public static String replaceUpToThirdHyphen(String input, String replacement) {
        // 检查输入是否为空
        if (input == null || input.isEmpty()) {
            return input;
        }

        int hyphenCount = 0;
        int index = 0;

        // 找到第三个"-"的位置
        while (index < input.length() && hyphenCount < 3) {
            if (input.charAt(index) == '-') {
                hyphenCount++;
            }
            index++;
        }

        // 如果找到至少三个"-"，进行替换 - 1
        if (hyphenCount >= 3) {
            return replacement + input.substring(index);
        } else {
            // 如果不足三个"-"，返回原字符串
            return input;
        }
    }

}
